package cn.zmit.mydemo10;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;

/**
 * Created by xiefan on 2016/6/23.
 */
public class RegisterActivity extends Activity implements View.OnClickListener {
    private EditText mEtPhone;
    private EditText mEtPwdNew;
    private EditText mEtPwdConfirm;
    private EditText mEtPhoneCode;
    private Button mBtnPhoneCode;
    private Button mBtnSubmit;
    private CheckBox mCbAgreement;
    private TimeCount time;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initView();
    }

    private void initView() {
        time = new TimeCount(60000, 1000);
        mEtPhone = (EditText) findViewById(R.id.et_phone);
        mEtPhoneCode = (EditText) findViewById(R.id.et_phonecode);
        mEtPwdNew = (EditText) findViewById(R.id.et_pwd_new);
        mEtPwdConfirm = (EditText) findViewById(R.id.et_pwd_confirm);
        mBtnPhoneCode = (Button) findViewById(R.id.btn_phonecode);
        mBtnPhoneCode.setOnClickListener(this);
        mCbAgreement = (CheckBox) findViewById(R.id.cb_agreement);
        mCbAgreement.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    mBtnSubmit.setClickable(true);
                } else {
                    mBtnSubmit.setClickable(false);
                }
            }
        });
        mBtnSubmit = (Button) findViewById(R.id.btn_submit);
        mBtnSubmit.setOnClickListener(this);
        mBtnSubmit.setClickable(false);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_phonecode:
                String phone = mEtPhone.getText().toString();
                if (phone.isEmpty()) {
                    Toast.makeText(RegisterActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                    Log.i("Main", "手机号不能为空");
                } else {
                    postPhoneCode(phone, "1");
                }
                break;
            case R.id.btn_submit:
                toSubmit();
                break;
        }
    }

    /**
     * 提交
     */
    private void toSubmit() {
        Log.i("Main", "toSubmit()");
        String phone = mEtPhone.getText().toString();
        String phoneCode = mEtPhoneCode.getText().toString();
        String pwdNew = mEtPwdNew.getText().toString();
        String pwdConfirm = mEtPwdConfirm.getText().toString();
        Log.i("Main", "phone:" + phone + "phoneCode" + phoneCode + "   password_new:" + pwdNew + "password_confirm" + pwdConfirm);
        if (phone.isEmpty() || phoneCode.isEmpty() || pwdNew.isEmpty() || pwdConfirm.isEmpty()) {
            Toast.makeText(RegisterActivity.this, "不能为空", Toast.LENGTH_SHORT).show();
        } else if (!pwdNew.equals(pwdConfirm)) {
            Toast.makeText(RegisterActivity.this, "密码不一致，请重新输入", Toast.LENGTH_SHORT).show();
        } else {
            posrRegister(phone, phoneCode, pwdNew, pwdConfirm);
        }
    }

    private void posrRegister(String phone, String phoneCode, String pwdNew, String pwdConfirm) {
        Log.i("Main", "posrRegister()");
        String url = "http://www.b.iffresh.com/webservice/auth/register";

        OkHttpUtils
                .post()
                .url(url)
                .addParams("phone", phone)
                .addParams("n_pwd", pwdNew)
                .addParams("f_pwd", pwdConfirm)
                .addParams("sale", phoneCode)
                .addParams("invitation_phone", "")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("Main", "onError:" + e);
                        Toast.makeText(RegisterActivity.this, "Error:" + e, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        String errorCode = null;
                        Log.i("Main", "onResponse:" + response);
                        try {
                            JSONObject mJsonObject = new JSONObject(response);
                            errorCode = mJsonObject.getString("errorCode");
                            Log.i("Main", "errorCode:" + errorCode);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (errorCode.equals("0")) {
                            Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                            Log.i("Main", "注册成功");
                        } else {
                            Toast.makeText(RegisterActivity.this, "Error:" + response, Toast.LENGTH_SHORT).show();
                            Log.i("Main", "注册失败：" + response);
                        }
                    }
                });
    }

    /**
     * 获取验证码
     */
    private void postPhoneCode(String phone, String phoneType) {
        Log.i("Main", "postPhoneCode()");
        Log.i("Main", "phone:" + phone + "   phoneType:" + phoneType);
        String url = "http://www.b.iffresh.com/webservice/auth/sendPhoneCode";
        OkHttpUtils
                .post()
                .url(url)
                .addParams("phone", phone)
                .addParams("phoneType", phoneType)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("Main", "onError:" + e);
                        Toast.makeText(RegisterActivity.this, "Error:" + e, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        String errorCode = null;
                        Log.i("Main", "onResponse:" + response);
                        try {
                            JSONObject mJsonObject = new JSONObject(response);
                            errorCode = mJsonObject.getString("errorCode");
                            Log.i("Main", "errorCode:" + errorCode);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (errorCode.equals("0")) {
                            time.start();
                            Toast.makeText(RegisterActivity.this, "验证码发送成功", Toast.LENGTH_SHORT).show();
                            Log.i("Main", "验证码发送成功");
                            RegisterActivity.this.finish();
                        } else {
                            Toast.makeText(RegisterActivity.this, "Error:" + response, Toast.LENGTH_SHORT).show();
                            Log.i("Main", "验证码发送失败:" + response);
                        }
                    }
                });
    }

    /**
     * 倒计时
     */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            mBtnPhoneCode.setText("获取验证码");
            mBtnPhoneCode.setClickable(true);
            mBtnPhoneCode.setBackground(getResources().getDrawable(R.drawable.selector_btn));

        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            mBtnPhoneCode.setClickable(false);//防止重复点击
            mBtnPhoneCode.setText(millisUntilFinished / 1000 + "s");
            mBtnPhoneCode.setBackground(getResources().getDrawable(R.drawable.shape_button_no));
        }

    }

}
